// 声明全局uni
declare const uni: any;
// import CryptoJS from 'crypto-js'
// import smcrypto , { sm3 } from "sm-crypto";


// 这个函数使用异或运算来加密和解密字符串。
const xorEncryptDecrypt = (input: string, key: string) => {
  let output = '';
  for (let i = 0; i < input.length; i++) {
    let charCode = input.charCodeAt(i) ^ key.charCodeAt(i % key.length);
    output += String.fromCharCode(charCode);
  }
  return output;
}

// 测试加解密函数
// const plaintext = 'Hello, World! 你好呀，112233';
// const key = 'mySecretKey'; // 密钥，确保密钥的长度足够

// const encryptedText = xorEncryptDecrypt(plaintext, key);
// console.log('Encrypted:', encryptedText);

// const decryptedText = xorEncryptDecrypt(encryptedText, key);
// console.log('Decrypted:', decryptedText);



/**
 * uni.showLoading 二次封装
 * 
 * https://uniapp.dcloud.io/api/ui/prompt?id=showtoast
 */
export const ShowLoading = (title = '加载中', mask = true, param = {
  success() { },
  fail() { },
  complete() { }
}) => {
  uni.showLoading({
    title,
    mask,
    ...param
  });
}

/**
 * 隐藏 showLoading
 */
export const HideLoading = () => uni.hideLoading();


export const Toast = (title: string, cb?: () => Function) => {
  uni.showToast({
    icon: "none",
    position: "bottom",
    title,
    complete() {
      cb instanceof Function && cb()
    }
  });
}

/**
 * 这个函数用于显示一个确认弹窗，并在用户点击确认后执行回调函数。
 * @param {string} title
 * @param {string} content
 * @param {() => Function} cb
 * @constructor
 */
export const Confirm = (title: string, content: string, cb?: () => void): void => {
  uni.showModal({
    title,
    content,
    success(res: any) {
      if (res.confirm) {
        cb instanceof Function && cb()
      }
    }
  });
}

/**
 * 是一个小程序的自动更新函数
 * @constructor
 */
export const MiniProgramUpdate = () => {
  // #ifndef H5 || APP
  const updateManager: UniApp.UpdateManager = uni.getUpdateManager();
  updateManager.onCheckForUpdate((res: { hasUpdate: any; }) => {
    // 请求完新版本信息的回调
    if (res.hasUpdate) {
      updateManager.onUpdateReady((res: any) => {
        Confirm('更新提示', '检测到新版本', () => {
          updateManager.applyUpdate();
        })
      });
    }
  });
  updateManager.onUpdateFailed((err: Error) => {
    // 新的版本下载失败
    Toast('更新失败，请稍后再试')
  });
  // #endif
}

/**
 * 深拷贝数组
 * @param arr 数据源
 */
export const removeDuplicate = (arr: any[]) => {
  return [...new Set(arr.map(e => JSON.stringify(e)))].map(e => JSON.parse(e))
}

/**
 * 判断当前是不是一个函数 如果是就执行,
 * @param Fun
 * @param objFunc
 */

export const isFunc = (Fun: () => void, ...objFunc: any[]) => {
  if (Fun instanceof Function) {
    Fun();
    if (Array.isArray(objFunc)) {
      for (let key in objFunc) {
        objFunc[key] instanceof Function && objFunc[key]();
      }
    }
  }
}

export const isNull: Array<null | undefined | string> = [null, undefined, '', ' ', 'null', 'undefined', 'Null', 'Undefined']

// 设置加密
// export const EncryptionCryptoJS = (data: any) => CryptoJS.AES.encrypt(JSON.stringify(data), import.meta.env.VITE_APP_BASE_StorageCryptoAppSecret).toString();
export const EncryptionCryptoJS = (data: any) => xorEncryptDecrypt(JSON.stringify(data), import.meta.env.VITE_APP_BASE_StorageCryptoAppSecret)
// export const EncryptionCryptoJS = (data: any) => data

// 解密
export const EecryptionCryptoJS = (data: any) => xorEncryptDecrypt(data, import.meta.env.VITE_APP_BASE_StorageCryptoAppSecret)
// export const EecryptionCryptoJS = (data: any) => data


//存储数据
export const SetStorage = (key: string, data: string | object | number) => {
  uni.setStorageSync(key, import.meta.env.VITE_APP_BASE_StorageCrypto === 'true' ? EncryptionCryptoJS(data) : data);
}


// 获取数据
export const GetStorage = (key: string) => {
  const s = uni.getStorageSync(key)
  try {
    return import.meta.env.VITE_APP_BASE_StorageCrypto === 'true' ? (isNull.includes(s) === false ? JSON.parse(EecryptionCryptoJS(s)) : EecryptionCryptoJS(s)) : s
  } catch (e) {
    return import.meta.env.VITE_APP_BASE_StorageCrypto === 'true' ? (isNull.includes(s) === false ? EecryptionCryptoJS(s) : EecryptionCryptoJS(s)) : s
  }
};

// 删除
export const RemoveStorage = (key: string) => uni.removeStorageSync(key)

export const ClearAll = () => uni.clearStorageSync();

//防抖：在事件被触发n秒后再执行回调，如果在这n秒内又被触发，则重新计时。 
export function Debounce(fun: { id: number | undefined; call: (arg0: any, arg1: any) => void; }, delay = 200) {
  return function (args: any) {
    //@ts-expect-error
    let that = this;
    let _args = args;
    clearTimeout(fun.id);
    //@ts-ignore
    fun.id = setTimeout(() => {
      fun.call(that, _args)
    }, delay)
  }
}

//节流：规定在一个单位时间内，只能触发一次函数。如果这个单位时间内触发多次函数，只有一次生效。
export function Throttle(fn: Function, delay = 200) {
  let timer = true;
  return (args: Array<any>) => {
    //@ts-expect-error
    let that = this;
    let _args = arguments;
    if (!timer) {
      return false;
    }
    timer = false;
    setTimeout(() => {
      fn.apply(that, _args)
      timer = true;
    }, delay)
  }
}

/**
 * 获取路由参数 @param {string  参数名}
 */
export const GetUrlKey = (name: string | number) => {

  let routes = getCurrentPages(); // 获取当前打开过的页面路由数组
  let curRoute = routes[routes.length - 1] // 获取当前页面路由，也就是最后一个打开的页面路由
  console.log(routes);

  return {
    curRoute
    // }curRoute.options[name]

  }
}


/**
 * 
 * @param url url地址
 * @param getKey 获取url上面的可以
 * @returns 
 */
export const getLocationSearch = (url: string, getKey?: string): any => {
  if (url && url.includes("https://") || url.includes("http://")) {
    interface urlkey {
      [key: string]: string
    }
    const [, search] = url.split('?'), urlQuer = search?.split('&'), searchdata: urlkey = {}
    if (Array.isArray(urlQuer)) {
      for (let i = 0; i < urlQuer.length; i++) {
        const [key, data] = urlQuer[i].split('=')
        // 兼容 匹配内容如果有汉字就转译，没有就不管
        searchdata[key] = data && /[\u4e00-\u9fa5]/gm.test(data) === false ? decodeURIComponent(data) : data;
      }
      return getKey ? searchdata[getKey] : searchdata
    }
  } else {
    throw 'getLocationSearch 需要一个完整得http的url地址'
  }
}

/**
 * 获取随机数
 * @param n 随机次数
 * @returns 
 */
export const randomCoding = (n = 6): string => {
  //创建26个字母数组
  let z = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T',
    'U', 'V', 'W', 'X', 'Y', 'Z'
  ]; //toUpperCase() 转大写
  let Z = ['z', 'b', 'c', 'c', 'e', 'f', 'g', 'h', 'i', 'j', 'l', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't',
    'u', 'v', 'w', 'x', 'y', 'z'
  ]; //toLowerCase() 转小写
  let arr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, ...z, ...Z],
    idvalue = ''; //这个值可以改变的，对应的生成多少个字母，根据自己需求所改
  for (let i = 0; i < n; i++) {
    idvalue += arr[Math.floor(Math.random() * arr.length)];
  }
  return idvalue;
}


export const EPlatform = {
  /**App*/
  AppPlus: 'APP-PLUS',
  /**App nvue*/
  AppPlusNvue: 'APP-PLUS-NVUE',
  /**H5*/
  H5: 'H5',
  /**微信小程序*/
  MpWeixin: 'MP-WEIXIN',
  /**支付宝小程序*/
  MpAlipay: 'MP-ALIPAY',
  /**百度小程序*/
  MpBaidu: 'MP-BAIDU',
  /**字节跳动小程序*/
  MpToutiao: 'MP-TOUTIAO',
  /**QQ小程序*/
  MpQq: 'MP-QQ',
  /**360小程序*/
  Mp360: 'MP-360',
  /**微信小程序/支付宝小程序/百度小程序/字节跳动小程序/QQ小程序/360小程序*/
  Mp: 'MPAll',
  /**快应用通用(包含联盟、华为)*/
  QuickappWebview: 'quickapp-webview',
  /**快应用联盟*/
  QuickappWebviewUnion: 'quickapp-webview-union',
  /**快应用华为*/
  QuickappWebviewHuawei: 'quickapp-webview-huawei',
}

/**使用条件编译获取平台信息*/
function ifDefPlatform() {
  let platform;

  //#ifdef APP-PLUS
  platform = EPlatform.AppPlus
  //#endif

  //#ifdef APP-PLUS-NVUE
  platform = EPlatform.AppPlusNvue
  //#endif

  //#ifdef H5
  platform = EPlatform.H5
  //#endif

  //#ifdef MP-WEIXIN
  platform = EPlatform.MpWeixin
  //#endif

  //#ifdef MP-ALIPAY
  platform = EPlatform.MpAlipay
  //#endif

  //#ifdef MP-BAIDU
  platform = EPlatform.MpBaidu
  //#endif

  //#ifdef MP-TOUTIAO
  platform = EPlatform.MpToutiao
  //#endif

  //#ifdef MP-QQ
  platform = EPlatform.MpQq
  //#endif

  //#ifdef MP-360
  platform = EPlatform.Mp360
  //#endif

  //#ifdef MP
  platform = EPlatform.Mp
  //#endif

  //#ifdef quickapp-webview
  platform = EPlatform.QuickappWebview
  //#endif

  //#ifdef quickapp-webview-union
  platform = EPlatform.QuickappWebviewUnion
  //#endif

  //#ifdef quickapp-webview-huawei
  platform = EPlatform.QuickappWebviewHuawei
  //#endif

  return platform
}

/**平台类型*/
export const Platform = ifDefPlatform()
/**默认导出平台类型*/
// export default Platform
// 移动端H5
export const isH5 = Platform === EPlatform.H5
// APP 仅限uni打包出来的APP
export const isApp = Platform === EPlatform.AppPlus
// 微信小程序
export const isMpWeixin = Platform === EPlatform.MpWeixin
//判断当前是否是微信h5
//#ifdef H5
// export const isWXh5 = String(navigator?.userAgent?.toLowerCase()?.match(/MicroMessenger/i)) === "micromessenger"
export const isWXh5 = /MicroMessenger/.test(window?.navigator?.userAgent)
// 支付宝H5
export const isAliPay = /AlipayClient/.test(window?.navigator?.userAgent)
//#endif

export default {
  randomCoding,
  ShowLoading,
  HideLoading,
  Toast,
  SetStorage,
  GetStorage,
  RemoveStorage,
  isFunc,
  getLocationSearch,
  ClearAll,
  GetUrlKey,
}
